{% extends "base.html" %}

{% block content %}
<div class="page-title">
    <h3>在下方输入要修改的商品的编号：</h3>
</div>
<div class="form-container">
    <form id="modify-product-form">
        <label for="product_id">商品编号（此项仅作查找之用，若想修改本项请在下方进行）：</label>
        <input type="text" id="product_id" name="product_id" class="input-field" required><br>
        <button type="button" class="login-button" id="search-button">查找</button>
        <div id="modify-fields" style="display:none;">
            <label for="product_name">商品名称：</label>
            <input type="text" id="product_name" name="product_name" class="input-field" required><br>
            <label for="product_price">商品单价：</label>
            <input type="number" id="product_price" name="product_price" class="input-field" required><br>
            <label for="supplier_id">供应商编号：</label>
            <input type="text" id="supplier_id" name="supplier_id" class="input-field" required><br>
            <label for="product_description">商品简介：</label>
            <textarea id="product_description" name="product_description" class="input-field"></textarea><br>
            <label for="remark">备注：</label>
            <textarea id="remark" name="remark" class="input-field"></textarea><br>
            <label for="new_product_id">新的商品编号（如不修改请留空）：</label>
            <input type="text" id="new_product_id" name="new_product_id" class="input-field"><br>
            <div class="button-container">
                <button type="submit" class="login-button">保存</button>
                <button type="reset" class="login-button" style="background-color: grey;">重置</button>
            </div>
        </div>
    </form>
</div>

<script>
    document.getElementById('search-button').addEventListener('click', function() {
        var productId = document.getElementById('product_id').value;
        if (productId) {
            fetch(`/api/products/${productId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        alert('该商品编号不存在');
                        document.getElementById('modify-fields').style.display = 'none';
                    } else {
                        document.getElementById('product_name').value = data.商品名称;
                        document.getElementById('product_price').value = data.商品单价;
                        document.getElementById('supplier_id').value = data.供应商编号;
                        document.getElementById('product_description').value = data.商品简介;
                        document.getElementById('remark').value = data.备注;
                        document.getElementById('modify-fields').style.display = 'block';
                    }
                }).catch(error => {
                    console.error('Error:', error);
                    alert('查找商品失败');
                });
        } else {
            alert('请输入商品编号');
            document.getElementById('modify-fields').style.display = 'none';
        }
    });

    document.getElementById('modify-product-form').addEventListener('submit', function(event) {
        event.preventDefault();

        var productId = document.getElementById('product_id').value;
        var newProductId = document.getElementById('new_product_id').value;
        const formData = new FormData(this);
        const data = Object.fromEntries(formData.entries());

        if (newProductId && newProductId !== productId) {
            if (!confirm('此次修改涉及商品编号，是否确认修改？')) {
                return;
            }
            data.new_product_id = newProductId;
        }

        fetch(`/api/products/${productId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }).then(response => {
            if (response.ok) {
                alert('商品修改成功');
                this.reset();
                document.getElementById('modify-fields').style.display = 'none';
            } else {
                response.json().then(data => {
                    alert('修改商品失败: ' + data.error);
                });
            }
        }).catch(error => {
            console.error('Error:', error);
            alert('修改商品失败');
        });
    });

    document.querySelector('button[type="reset"]').addEventListener('click', function(event) {
        if (!confirm('是否确定重置已输入信息？')) {
            event.preventDefault();
        }
    });
</script>
{% endblock %}
